﻿Public Class frm_compra
    Dim check As New Validar
    Dim accesoDatosProv As New AccesoDatos("Proveedor")
    Dim accesoDatosTipoProd As New AccesoDatos("TipoProd")
    Dim accesoDatosTipoTela As New AccesoDatos("TipoTela")
    Dim accesoDatosProd As New AccesoDatos("Producto")
    Dim accesoDatosCompra As New AccesoDatos("Compra")
    Dim accesoDatosDetalleCompra As New AccesoDatos("Detalle_Compra")


    Dim idProdAgreg As Integer

    Private Sub cargarCombo(ByRef combo As ComboBox, ByRef tablaACargar As Data.DataTable, ByVal indice As String, ByVal campo As String)
        combo.DataSource = Nothing
        combo.DataSource = tablaACargar
        combo.ValueMember = indice
        combo.DisplayMember = campo

    End Sub

    Public Sub limpiarFormCompra()
        dgv_producto.DataSource = Nothing
        cmb_tipoProd.SelectedValue = -1
        cmb_tipoTela.SelectedValue = -1
        cmb_proveedor.Enabled = False

    End Sub

    Private Sub frm_compra_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        If MessageBox.Show("¿Está seguro que desea salir?", "Confirmación", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
            e.Cancel = False
            frm_menu.Show()
        Else
            e.Cancel = True
        End If
    End Sub

    Private Sub frm_compra_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Dim consulta As String = "SELECT MAX(idCompra) + 1 AS 'idCompra' FROM Compra"
        lbl_mostrarFecha.Text = DateTime.Today
        Dim tabla As New DataTable
        tabla = accesoDatosCompra.consulta(consulta)
        txt_idCompra.Text = tabla.Rows(0)("idCompra")


        cargarCombo(cmb_proveedor, accesoDatosProv.leerTabla("Proveedor"), "idProveedor", "nombre")
        cargarCombo(cmb_tipoProd, accesoDatosTipoProd.leerTabla("TipoProd"), "idTipoProd", "nombre")
        cargarCombo(cmb_tipoTela, accesoDatosTipoTela.leerTabla("TipoTela"), "idTipoTela", "nombre")

        cmb_proveedor.SelectedIndex = -1
        cmb_tipoProd.SelectedIndex = -1
        cmb_tipoTela.SelectedIndex = -1
        txt_descrip.Text = ""
        dgv_producto.DataSource = Nothing

        cmb_tipoProd.Enabled = False
        cmb_tipoTela.Enabled = False
        cmd_agregarProd.Enabled = False
        cmd_confirmarCompra.Enabled = False
        cmd_nuevoProd.Enabled = False
    End Sub

    Private Sub cargarGrillaProducto()
        dgv_producto.DataSource = Nothing
        Dim tabla As New Data.DataTable
        Dim consul As String = "SELECT Producto.idProducto AS 'ID Producto', Proveedor.nombre AS 'Proveedor', TipoProd.nombre AS 'Tipo Producto', TipoTela.nombre AS 'Tela', Producto.descripcion AS 'Descripción', Producto.PrecioCosto AS 'Precio' FROM Producto INNER JOIN Proveedor ON Producto.idProveedor = Proveedor.idProveedor INNER JOIN TipoProd ON Producto.idTipoProd = TipoProd.idTipoProd INNER JOIN TipoTela ON Producto.idTipoTela = TipoTela.idTipoTela WHERE Producto.idProveedor = " & cmb_proveedor.SelectedValue

        If IsNumeric(cmb_tipoProd.SelectedValue) Then
            consul &= " AND producto.idTipoProd = " & cmb_tipoProd.SelectedValue
        End If
        If IsNumeric(cmb_tipoTela.SelectedValue) Then
            consul &= " AND producto.idTipoTela = " & cmb_tipoTela.SelectedValue
        End If
        If txt_descrip.Text <> "" Then
            consul &= " AND producto.descripcion LIKE '%" & txt_descrip.Text & "%'"
        End If

        tabla = accesoDatosProd.consulta(consul)
        dgv_producto.DataSource = tabla
    End Sub

    Private Sub cmb_proveedor_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmb_proveedor.SelectedIndexChanged
        If IsNumeric(cmb_proveedor.SelectedValue) Then
            cmb_tipoProd.Enabled = True
            cmb_tipoTela.Enabled = True
            cmd_nuevoProd.Enabled = True
            cmb_tipoProd.SelectedIndex = -1
            cmb_tipoTela.SelectedIndex = -1
            txt_descrip.Text = ""
            cargarGrillaProducto()
        End If
    End Sub

    Private Sub cmb_tipoProd_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmb_tipoProd.SelectedIndexChanged
        If IsNumeric(cmb_tipoProd.SelectedValue) Then
            cargarGrillaProducto()
        End If
    End Sub

    Private Sub cmb_tipoTela_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmb_tipoTela.SelectedIndexChanged
        If IsNumeric(cmb_tipoTela.SelectedValue) Then
            cargarGrillaProducto()
        End If
    End Sub

    Private Sub txt_descrip_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txt_descrip.TextChanged
        cargarGrillaProducto()
    End Sub



    Private Sub dgv_producto_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgv_producto.CellClick
        cmd_agregarProd.Enabled = True
    End Sub

    Private Sub cmd_agregarProd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmd_agregarProd.Click
        Dim errorExist As Boolean = False
        idProdAgreg = dgv_producto.CurrentRow.Cells(0).Value

        For i As Integer = 0 To dgv_compra.RowCount - 1
            If dgv_compra.Rows(i).Cells(1).Value = idProdAgreg Then
                MessageBox.Show("El producto que desea ingresara ya ha sido agregado a la compra", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
                errorExist = True
                cmb_tipoProd.SelectedIndex = -1
                cmb_tipoTela.SelectedIndex = -1
                txt_descrip.Text = ""
            End If
        Next
        If errorExist = False Then
            frm_talles.recibirId(idProdAgreg)
            frm_talles.ShowDialog()
            cmd_confirmarCompra.Enabled = True

        End If

    End Sub

    Public Sub cargarCompra(ByRef grilla As DataGridView)
        frm_talles.Hide()
        cmd_agregarProd.Enabled = False
        Dim cantidad As Integer
        Dim producto As String
        Dim descrip As String
        Dim precio As Double
        Dim talle As String
        Dim importe As String
        For i As Integer = 0 To grilla.RowCount - 1
            cantidad = grilla.Rows(i).Cells(1).Value
            producto = dgv_producto.CurrentRow.Cells(0).Value
            descrip = dgv_producto.CurrentRow.Cells(2).Value & " "
            descrip &= dgv_producto.CurrentRow.Cells(3).Value & " "
            descrip &= dgv_producto.CurrentRow.Cells(4).Value & " "
            descrip &= "talle " & grilla.Rows(i).Cells(0).Value
            precio = CDbl(dgv_producto.CurrentRow.Cells(5).Value)
            importe = precio * cantidad
            talle = grilla.Rows(i).Cells(2).Value
            dgv_compra.Rows.Add(cantidad, producto, descrip, precio, talle, importe)
        Next

        Dim total As Double = 0

        For i As Integer = 0 To dgv_compra.RowCount - 1
            total = total + CDbl(dgv_compra.Rows(i).Cells(5).Value)
        Next

        lbl_mostrarMontoTotal.Text = total

    End Sub

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        lbl_mostrarHora.Text = Format(Now, "HH:mm:ss")
    End Sub

    Private Function generarStringValoresCompra() As String
        Dim valores As String = "idProveedor =" & cmb_proveedor.SelectedValue
        valores &= ", fecha =" & lbl_mostrarFecha.Text
        valores &= ", montoTotal =" & lbl_mostrarMontoTotal.Text

        Return valores
    End Function

    Private Function generarStringValoresDetalleCompra(ByVal fila As Integer) As String
        Dim valores As String = "idCompra =" & txt_idCompra.Text
        valores &= ", idTalle =" & dgv_compra.Rows(fila).Cells(4).Value
        valores &= ", idProducto =" & dgv_compra.Rows(fila).Cells(1).Value
        valores &= ", cantidad =" & dgv_compra.Rows(fila).Cells(0).Value
        valores &= ", precioUnitario =" & dgv_compra.Rows(fila).Cells(3).Value

        Return valores
    End Function

    Private Sub cmd_confirmarCompra_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmd_confirmarCompra.Click
        If MessageBox.Show("Esta seguro que desea confirmar la compra", "Confirmar", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
            accesoDatosCompra.insertar(True, generarStringValoresCompra())
            For i As Integer = 0 To dgv_compra.RowCount - 1
                accesoDatosDetalleCompra.insertar(True, generarStringValoresDetalleCompra(i))
                accesoDatosDetalleCompra.actualizarStockCompra(dgv_compra.Rows(i).Cells(1).Value, dgv_compra.Rows(i).Cells(4).Value, dgv_compra.Rows(i).Cells(0).Value)
            Next
            MessageBox.Show("Compra realizada con éxito", "Nueva Compra", MessageBoxButtons.OK, MessageBoxIcon.Information)
            cmb_proveedor.SelectedIndex = -1
            cmb_proveedor.Enabled = True
            cmb_proveedor.Focus()
            cmb_tipoProd.SelectedIndex = -1
            cmb_tipoTela.SelectedIndex = -1
            txt_descrip.Text = ""
            dgv_producto.DataSource = Nothing

            dgv_compra.Rows.Clear()
            dgv_producto.Rows.Clear()

            cmb_tipoProd.Enabled = False
            cmb_tipoTela.Enabled = False
            cmd_agregarProd.Enabled = False
            cmd_confirmarCompra.Enabled = False
            cmd_nuevoProd.Enabled = False
            lbl_mostrarMontoTotal.Text = ""

        End If

    End Sub

Private Sub cmd_cancelar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmd_cancelar.Click

        cmb_proveedor.SelectedIndex = -1
        cmb_proveedor.Enabled = True
        cmb_tipoProd.SelectedIndex = -1
        cmb_tipoTela.SelectedIndex = -1
        txt_descrip.Text = ""
        dgv_producto.DataSource = Nothing

        dgv_compra.Rows.Clear()
        dgv_producto.Rows.Clear()

        cmb_tipoProd.Enabled = False
        cmb_tipoTela.Enabled = False
        cmd_agregarProd.Enabled = False
        cmd_confirmarCompra.Enabled = False
        cmd_nuevoProd.Enabled = False
        lbl_mostrarMontoTotal.Text = ""
    End Sub

    Private Sub cmd_nuevoProd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmd_nuevoProd.Click
        frm_prod.ShowDialog()
    End Sub


    Private Sub cmd_salir_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmd_salir.Click
        Me.Close()
    End Sub
End Class